from fastapi import FastAPI, BackgroundTasks, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import os
from dotenv import load_dotenv
from typing import Optional
import uuid
from datetime import datetime

# Load environment variables
load_dotenv()

# Initialize FastAPI app
app = FastAPI(
    title="AI Video Hub",
    description="AI-powered video generation and editing platform",
    version="0.1.0"
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Import models and services after app initialization to avoid circular imports
from models.project import Project, ProjectCreate
from models.video import Video, VideoCreate
from database import init_db, get_db
from services.video_generator import VideoGeneratorService
from services.llm_service import LLMService
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse

# Initialize services
llm_service = LLMService()
video_generator = VideoGeneratorService(llm_service)

@app.on_event("startup")
async def startup_event():
    """Initialize database on startup"""
    init_db()
    
# 添加静态文件服务 - 修正路径
app.mount("/static", StaticFiles(directory="frontend"), name="static")

# 服务前端文件
@app.get("/")
async def serve_frontend():
    return FileResponse("frontend/index.html")

@app.get("/frontend/")
async def serve_frontend_path():
    return FileResponse("frontend/index.html")

# 服务其他前端静态文件
@app.get("/{filename}")
async def serve_static_files(filename: str):
    if filename in ["styles.css", "script.js"]:
        return FileResponse(f"frontend/{filename}")
    raise HTTPException(status_code=404, detail="File not found")

@app.post("/projects/")
async def create_project(project: ProjectCreate):
    """Create a new video project"""
    db = next(get_db())
    try:
        new_project = Project(
            id=str(uuid.uuid4()),
            title=project.title,
            description=project.description,
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )
        db.add(new_project)
        db.commit()
        db.refresh(new_project)
        return new_project
    finally:
        db.close()

@app.get("/projects/{project_id}")
async def get_project(project_id: str):
    """Get a specific project by ID"""
    db = next(get_db())
    try:
        project = db.query(Project).filter(Project.id == project_id).first()
        if not project:
            raise HTTPException(status_code=404, detail="Project not found")
        return project
    finally:
        db.close()

@app.get("/projects/")
async def get_projects():
    """Get all projects"""
    db = next(get_db())
    try:
        projects = db.query(Project).all()
        return projects
    finally:
        db.close()

@app.get("/videos/")
async def get_videos():
    """Get all videos"""
    db = next(get_db())
    try:
        videos = db.query(Video).all()
        return videos
    finally:
        db.close()

@app.post("/generate-video-from-text/")
async def generate_video_from_text(
    request: dict,
    background_tasks: BackgroundTasks
):
    """Generate a video from text prompt using AI"""
    try:
        prompt = request.get("prompt", "")
        project_id = request.get("project_id", None)
        
        if not prompt:
            raise HTTPException(status_code=400, detail="Prompt is required")
        
        # Generate video asynchronously
        video_id = str(uuid.uuid4())
        output_path = f"videos/{video_id}.mp4"
        
        print(f"🎬 准备生成视频: {prompt}")
        print(f"📁 输出路径: {output_path}")
        
        # Add background task to generate video
        background_tasks.add_task(
            video_generator.generate_from_text,
            prompt,
            output_path,
            project_id
        )
        
        return {
            "video_id": video_id,
            "status": "processing",
            "output_path": output_path,
            "message": "Video generation started"
        }
    except Exception as e:
        print(f"❌ 视频生成请求失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/upload-video/")
async def upload_video(
    file: UploadFile = File(...),
    project_id: Optional[str] = None
):
    """Upload a video file to a project"""
    try:
        # Validate file type
        if not file.content_type.startswith("video/"):
            raise HTTPException(status_code=400, detail="File must be a video")
        
        # Create unique filename
        file_extension = os.path.splitext(file.filename)[1]
        video_id = str(uuid.uuid4())
        file_path = f"videos/{video_id}{file_extension}"
        
        # Create videos directory if it doesn't exist
        os.makedirs("videos", exist_ok=True)
        
        # Save uploaded file
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # Create video record in database
        db = next(get_db())
        try:
            video = Video(
                id=video_id,
                filename=file.filename,
                file_path=file_path,
                project_id=project_id,
                size=len(content),
                created_at=datetime.utcnow()
            )
            db.add(video)
            db.commit()
            db.refresh(video)
        finally:
            db.close()
        
        return {
            "video_id": video_id,
            "filename": file.filename,
            "file_path": file_path,
            "size": len(content),
            "message": "Video uploaded successfully"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "timestamp": datetime.utcnow()}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
